package com.testing.login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "Logout")
public class Logout extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        String result="{";
        if(session.getAttribute("loginUser")!=null){
            result+= "\"msg\":\"注销用户"+session.getAttribute("loginUser")+"\",\"code\":\"2\"}";
            session.invalidate();
            //创建一个sessionCookie用于保存获取到的JSESSIONID的cookie
            Cookie sessionCookie=null;
            Cookie[] cookies = request.getCookies();
            if(cookies!=null)
            for (Cookie cookie : cookies) {
                //如果cookie的值是sessionid，则重置它的生命周期为0
                if(cookie.getValue().equals(session.getId())){
                    sessionCookie=cookie;
                }
            }
            //将sessionCookie重置生命周期为0
            sessionCookie.setMaxAge(0);
            //返回cookie
            response.addCookie(sessionCookie);
        }
        else{
            result+= "\"msg\":\"没有用户登录，将session失效\",\"code\":\"2\"}";
            session.invalidate();
        }
        response.getWriter().append(result);

    }
}
